
#include "debug.h"
#include "sms.h"
#include "Receivers.h"
#include "OS.h"
#include "App.h"
#include "sscanf.h"
#include "string.h"
#include "modem.h"
#include "storage.h"
#include "entrys.h"
#include "cmdp.h"
#include "dev.h"
#include "memmap.h"


/* Drive_Receivers; <  */
/* +CMTI: "SM",4 */
/*  > */

/* Drive_Receivers; */
/*  ===== BUFFER ========= */
/* [ */
/* +CMGR: "REC READ","+972526144338",,"12/02/26,15:31:02+08" */
/* G+t5oqt */

/* OK */
/* ] */

// ","+972526144338

typedef struct
{
		char phone[16];
		char text[128];
}sms_t;

sms_t sms;

char *p;
int sms_number;
char buf[24];
/* read sms each x time */
void sms_monitor ( void )
{
	int t;
	switch(APP.State )
	{
		case ASTE_START:
			DBG("\n%s; started\n",__FUNCTION__); 
			sms_number = -1;
			APP.State = ASTE_IDLE;
			
		case ASTE_IDLE:
			if ( Modem_Message )
			{                                    
				if ( s_scanf(Modem_Message, "\r\n+CMTI: \"SM\",%d", &sms_number) == 1 )
				{
					sprintf(buf, "AT+CMGR=%d", sms_number);
					//DBG("\n%s; buf: %s\n",__FUNCTION__,buf); 
				}
			}

			
			if ( sms_number != -1 && Modem_SendCommand(1,buf) )/* read sms */
			{ 
				t = -1;
				p = StrStr(modem_buf, "+CMGR:");
            //               +CMGR: "REC UNREAD","+972526144338","","12/02/28,14:15:13+08"
#ifdef   MODEM_TYPE__SIMCOM				
				if ( p && s_scanf(p, "+CMGR: \"%*s\",\"%s\",,\"%*s\"\r\n%s\r", buf, sms.text) )
#else					
				if ( p && s_scanf(p, "+CMGR: \"%*s\",\"%s\",\"\",\"%*s\"\r\n%s\r", buf, sms.text) )
#endif
				{
					t = StrLen(buf);
					t -= 9; /* 526144338 */
				
					// +972526144338
					StrCpy(sms.phone, "0");
					StrCat(sms.phone, &buf[t]);
					

					dbg("=======\n\r sms.phone: %s\n\r sms.text: %s\n\r=======\n\r", sms.phone, sms.text); 
					
					char passw[8], cmd[64];	  

					if ( storage.find(PHONE_LIST_0, sms.phone) > 0 ) 
					{
						DBG("storage.find: Phone: %s found\n", sms.phone);
						cmd_add_command(sms.text, DEV_SMS);
					}
					else				  /* if user not found, then format of command must be like 'passw command' (1234 R10)  */
					{
						dbg("USER NOT FOUND");
						if ( (s_scanf(sms.text, "%s %s", &passw, &cmd)) == 2 )
						{
							DBG("passw: '%s'; cmd: '%s'\n", passw, cmd);
							if ( storage.comp(ADDR_PASSW_1, passw, 4) ) 
							{
								DBG("password = OK\n");
								cmd_add_command(cmd, DEV_SMS);
							}
							else
							{
								DBG("wrong password!");
							}
						}
						else
						{
							DBG("SMS format is wrong\n");
						}
					}
		
					sprintf(buf, "AT+CMGD=%d", sms_number);
					DBG("\n%s; del: %s\n",__FUNCTION__,buf); 
					Modem_SendCommand(0,buf);
					sms_number = -1;
				}
			}
			break;	

/* 		case ASTE_FINISH: */
/* 			if ( (p = StrStr(ModemBuffer, "+CMGL:")) ) */
/* 			{ */
				
/* 			} */
/* 			else */
/* 			{ */
				
/* 			} */

/* 			break; */
			
	}
} 
